package com.tao.controller;

import com.alibaba.fastjson.JSONObject;
import com.tao.pojo.*;
import com.tao.service.brand.IbrandService;
import com.tao.service.color.IcolorService;
import com.tao.service.product.IproductService;
import com.tao.service.sku.IskuService;
import com.tao.service.storage.IstorageService;
import com.tao.util.MyFileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/product")
public class ProductController {
	@Autowired
	IbrandService brandService;
	@Autowired
	IcolorService colorService;
	@Autowired
	IstorageService storageService;
	@Autowired
	IproductService productService;
	@Autowired
	IskuService skuService;

	/**
	 * 包含了商品信息的展示和查询
	 * @param product  查询信息的保留  如果第一次进入到该页面 product为空，所以也无关紧要了
	 * @param map  用于返回页面视图的数据
     * @return
     */
	@RequestMapping("/show.do")
	public String show(ProductWithBLOBs product,ModelMap map) {
		System.out.println("TaoLog:"+"进入show.do");
		ProductExample productExample = new ProductExample();
		List<ProductWithBLOBs> products = productService.query(product, productExample);
		//设置page相关信息，关于分页的插件
		map.addAttribute("products",products);
		map.addAttribute("product",product);
		return "product/show";
	}

	@RequestMapping(value="/add.do",method=RequestMethod.GET)
	public String goAdd(ModelMap map){
		/*获取brand列表*/
		Brand brand = new Brand();
		brand.setWithPage(0);           //不分页
		BrandExample brandExample =new BrandExample();
		brandExample.createCriteria().andIsDelEqualTo(0);  //查询所有有效的品牌名
		List<Brand> brands = brandService.query(brand, brandExample);

		/*获取颜色列表*/
		ColorExample colorExample = new ColorExample();
		colorExample.createCriteria().andIsDelEqualTo(0);
		List<Color> colors = colorService.getColors(colorExample);

		/*获取内存列表*/
		//StorageExample.Criteria criteria = new StorageExample().createCriteria().andIsDelNotEqualTo(0);
		StorageExample storageExample = new StorageExample();
		List<Storage> storages = storageService.getStorage(storageExample);

		/*添加到视图解析器*/
		map.addAttribute("brands",brands); //返回到添加页面的视图
		map.addAttribute("colors",colors);
		map.addAttribute("storages",storages);
		return "product/add";
	}

	@RequestMapping(value="/add.do",method=RequestMethod.POST)
	public String doAdd(ProductWithBLOBs product ,HttpServletRequest req){
		/*因为该操作涉及到的数据库操作较多，需要使用事务进行处理*/
		//System.out.println("TaoLog:"+product);
		/*处理图片列表*/
		List<String> imageNames = new ArrayList<>();
		MultipartHttpServletRequest request = (MultipartHttpServletRequest) req;
		List<MultipartFile> images = request.getFiles("image");
		for (MultipartFile image : images){
			//System.out.println("TaoLog:"+image.getOriginalFilename());
			String fileName = MyFileUtils.upload(image);  //可以考虑后期用Json格式存储数据
			imageNames.add(fileName);
		}
		product.setImages(imageNames.toString().replaceAll("\\[", "").replaceAll("\\]", ""));

		/*插入商品其他信息*/
		int resultCode = productService.add(product);
		System.out.println(resultCode);

		return "redirect:show.do";
	}

	@RequestMapping("/upload.do")
	@ResponseBody
	public String upload(MultipartFile img){
		JSONObject json=new JSONObject();
		try {
			String str= MyFileUtils.upload(img);
			json.put("error", 0);
			json.put("url",MyFileUtils.IMG_SERVER+ str);
		} catch (Exception e) {
			json.put("error", 1);
			json.put("message","上传错误");
			e.printStackTrace();
		}
		return json.toJSONString();
	}

	@RequestMapping("/details.do")
	public String goDetails(int id,ModelMap map){
		map.addAttribute("id", id);
		return "product/product";
	}
	@RequestMapping(value = "/getProduct.do",produces = "application/json;charset=utf-8")
	@ResponseBody
	public String getProduct(int id){
		System.out.println("TaoLog:进入getProduct.do");
		ProductWithBLOBs product = productService.queryone(id);
		ColorExample colorExample=new ColorExample();
		StorageExample storageExample=new StorageExample();
		List<Integer> colors=new ArrayList<>();
		List<Integer> storages=new ArrayList<>();
		String[] colorarr= product.getColorList().split(",");
		for (String string : colorarr) {
			colors.add(Integer.parseInt(string));
		}
		colorExample.createCriteria().andIdIn(colors);
		List<Color> colorlist=colorService.getColors(colorExample);
		String[] storagearr= product.getStorageList().split(",");
		for (String string : storagearr) {
			storages.add(Integer.parseInt(string));
		}
		storageExample.createCriteria().andIdIn(storages);
		List<Storage> storagelist=storageService.getStorage(storageExample);
		product.setColors(colorlist);
		product.setStorages(storagelist);
		SkuExample skuExample=new SkuExample();
		skuExample.createCriteria().andProductIdEqualTo(id);
		List<Sku> skus= skuService.query(skuExample);
		product.setSkus(skus);
		return JSONObject.toJSONString(product);
	}

	/**
	 * 进入商品修改页面
	 * @param id
	 * @param map
     * @return
     */
	@RequestMapping(value = "/update.do",method = RequestMethod.GET)
	public String goUpdate(Integer id,ModelMap map){
		/*获取brand列表*/
		Brand brand = new Brand();
		brand.setWithPage(0);           //不分页
		BrandExample brandExample =new BrandExample();
		brandExample.createCriteria().andIsDelEqualTo(0);  //查询所有有效的品牌名
		List<Brand> brands = brandService.query(brand, brandExample);

		/*获取颜色列表*/
		ColorExample colorExample = new ColorExample();
		colorExample.createCriteria().andIsDelEqualTo(0);
		List<Color> colors = colorService.getColors(colorExample);

		/*获取内存列表*/
		//StorageExample.Criteria criteria = new StorageExample().createCriteria().andIsDelNotEqualTo(0);
		StorageExample storageExample = new StorageExample();
		List<Storage> storages = storageService.getStorage(storageExample);

		/*获取某个id号的商品*/
		ProductWithBLOBs product = productService.queryone(id);
		/*添加到视图解析器*/
		map.addAttribute("brands",brands); //返回到添加页面的视图
		map.addAttribute("colors",colors);
		map.addAttribute("storages",storages);
		map.addAttribute("product",product);
		return "product/update";
	}
	@RequestMapping(value = "update.do",method = RequestMethod.POST)
	public String doUpdate(ProductWithBLOBs product){
		productService.update(product);

		return "redirect:show.do";
	}
	@RequestMapping("/del")
	public String del(Integer id,Integer flag){
		System.out.println("TaoLog:"+id+","+flag);
		if(flag==1){
			//找回
			productService.unDel(id);
		}else if(flag==0){
			//删除
			productService.del(id);
		}

		return "redirect:show.do";
	}
}
